//
//  JimViewController.m
//  zuixin
//
//  Created by QJY on 14-8-23.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "JimViewController.h"
#import "DingSh.h"
#import "Header.h"
#import "FMDBManager.h"

#import "LogViewController.h"
@interface JimViewController ()

@end

@implementation JimViewController
{
    ABAddressBookRef addressBook;
    NSMutableArray *addressBookTemp;
    NSString *_nameString;
    DingSh * _addressBook;
    UIImageView *_imageview3;
    NSTimer *_tite;
    CFArrayRef allPeople;
    NSMutableArray *allPeopleMutArry;
    
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        allPeopleMutArry=[[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    dispatch_queue_t t = dispatch_queue_create(NULL, NULL);
    dispatch_async(t, ^{
        [self readAllPeoples];
        [self getAllPeople];
    });
    dispatch_async(dispatch_get_main_queue(), ^{
        [self textfi];
    });
    //    NSThread *thred=[[NSThread alloc]initWithTarget:self selector:@selector(getAllPeople) object:nil];
    //    [thred start];
}

-(void)getAllPeople
{
    
    FMDBManager* manager = [FMDBManager sharedManager];
    NSMutableArray* _dataArray = [manager getAllUsers];
    NSLog(@"%d",_dataArray.count);
    for(int i=0;i<[_dataArray count];i++)
    {
        NSString *name =((DingSh *)[_dataArray objectAtIndex:i]).name;
        
        NSString *mains =((DingSh *)[_dataArray objectAtIndex:i]).main;
        NSString *mobbi =((DingSh *)[_dataArray objectAtIndex:i]).mobile;
        NSString *homer =((DingSh *)[_dataArray objectAtIndex:i]).home;
        NSString *workd =((DingSh *)[_dataArray objectAtIndex:i]).work;
        NSString *other =((DingSh *)[_dataArray objectAtIndex:i]).other;
        NSString *teld =((DingSh *)[_dataArray objectAtIndex:i]).tel;
        
        NSMutableArray *cey =[[NSMutableArray alloc]initWithObjects:name,[self SwitchNsstring: mobbi],[self SwitchNsstring:mains],[self SwitchNsstring: homer],[self SwitchNsstring: workd],[self SwitchNsstring:other],[self SwitchNsstring:teld], nil];
        NSMutableArray *cey1;
        for(int i=0;i<cey.count;i++)
        {
            
            cey1=[[NSMutableArray alloc]initWithObjects:name,[self SwitchNsstring: mobbi],[self SwitchNsstring:mains],[self SwitchNsstring: homer],[self SwitchNsstring: workd],[self SwitchNsstring:other], nil];
            if ([cey1 containsObject:cey[6]]) {
                //NSInteger *numb=[cey1 indexOfObject:cey[6]];
                
            }
            else
            {
                cey1 =[[NSMutableArray alloc]initWithObjects:name,[self SwitchNsstring: mobbi],[self SwitchNsstring:mains],[self SwitchNsstring: homer],[self SwitchNsstring: workd],[self SwitchNsstring:teld], nil];
            }
        }
        [allPeopleMutArry addObject:cey1];
        
    }
    NSLog(@"dddsss%@",allPeopleMutArry);
    [[NSUserDefaults standardUserDefaults]setObject:allPeopleMutArry forKey:@"AllpeopNumber"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
}
-(NSString*)SwitchNsstring:(NSString*)string
{
    unichar temp;
    NSString *name=@"";
    
    for (int i=0; i<[string length]; i++) {
        temp=[string characterAtIndex:i];
       // NSLog(@"aaa%hu",temp);
        if (temp>='0'&&temp<='9') {
            name=[NSString stringWithFormat:@"%@%@",name,[NSString stringWithFormat:@"%C",temp]];
        }
    }
    return name;
    
}
-(void)textfi
{
    self.view.backgroundColor=[UIColor whiteColor];
    _imageview3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    if (DeviceHeight==568) {
        [_imageview3 setImage:[UIImage imageNamed:@"shanping1136.jpg"]];
    }
    else
    {
        [_imageview3 setImage:[UIImage imageNamed:@"shanping640.jpg"]];
    }
    [self.view addSubview:_imageview3];
    
    _tite= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
}
-(void)timer
{
    [_imageview3 removeFromSuperview];
    [_tite invalidate];
    [self presentViewController:[LogViewController alloc] animated:YES completion:^{
    }];
}
-(void)readAllPeoples
{
    ABAddressBookRef addressBooks = nil;
    
    if ([[ UIDevice currentDevice ]. systemVersion floatValue ]>= 6.0 ) {
        addressBooks = ABAddressBookCreateWithOptions ( NULL , NULL );
        dispatch_semaphore_t sema = dispatch_semaphore_create ( 0 );
        
        ABAddressBookRequestAccessWithCompletion (addressBooks, ^( bool granted, CFErrorRef error){ dispatch_semaphore_signal (sema);});
        dispatch_semaphore_wait (sema, DISPATCH_TIME_FOREVER );
    }else
    {
        addressBooks = ABAddressBookCreate ();
    }
    // 获取通讯录中的所有人
    allPeople = ABAddressBookCopyArrayOfAllPeople (addressBooks);
    // 通讯录中人数
    CFIndex nPeople = ABAddressBookGetPersonCount (addressBooks);
    NSLog(@"ddd%ld",nPeople);
    for ( NSInteger i = 0 ; i<nPeople; i++)
    {
        _addressBook = [[ DingSh alloc ] init ];
        // 获取个人
        ABRecordRef person = CFArrayGetValueAtIndex (allPeople, i);
        CFTypeRef abName = ABRecordCopyValue (person, kABPersonAddressProperty );
        
        CFTypeRef abLastName = ABRecordCopyValue (person, kABPersonLastNameProperty );
        
        CFStringRef abFullName = ABRecordCopyCompositeName (person);
        
        _nameString = ( __bridge NSString *)abName;
        
        NSString *lastNameString = ( __bridge NSString *)abLastName;
        
        if (( __bridge id )abFullName != nil ) {
            
            _nameString = ( __bridge NSString *)abFullName;
            
        } else {
            if (( __bridge id )abLastName != nil )
            {
                _nameString = [ NSString stringWithFormat : @"%@ %@" , _nameString, lastNameString];
            }
        }
        _addressBook. name = _nameString;
        _addressBook. recordID = ( int ) ABRecordGetRecordID (person);;
        
        ABPropertyID multiProperties[] = {
            
            kABPersonPhoneProperty ,
            
            kABPersonEmailProperty
            
        };
        NSInteger multiPropertiesTotal = sizeof (multiProperties) / sizeof ( ABPropertyID );
        for ( NSInteger j = 0 ; j < multiPropertiesTotal; j++) {
            ABPropertyID property = multiProperties[j];
            
            ABMultiValueRef valuesRef = ABRecordCopyValue (person, property);
            
            NSInteger valuesCount = 0 ;
            
            if (valuesRef != nil ) valuesCount = ABMultiValueGetCount (valuesRef);
            
            if (valuesCount == 0 ) {
                
                CFRelease (valuesRef);
                
                continue ;
            }
            // 获取电话号码和 email
            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
            for (int k = 0; k<ABMultiValueGetCount(phone); k++)
            {
                //获取电话Label
                NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
                NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
                _addressBook.tel =personPhone;
                NSLog(@"%@",personPhone);
                
                NSString *texe=[NSString stringWithFormat:@"%@:%@\n",personPhoneLabel,personPhone];
                if([texe hasPrefix:@"移动"]||[texe hasPrefix:@"手机"]||[texe hasPrefix:@"移动手机"]||[texe hasPrefix:@"电话"])
                {
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    _addressBook.mobile =df;
                }
                if([texe hasPrefix:@"工作传真"]||[texe hasPrefix:@"工作"])
                {NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    
                    _addressBook.work =df;
                }
                if( [texe hasPrefix:@"住宅传真"]||[texe hasPrefix:@"iPhone"])
                {
                    
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    
                    _addressBook.other =df;
                }
                
                if([texe hasPrefix:@"其他"]||[texe hasPrefix:@"传呼"])
                {
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    _addressBook.home =df;
                    NSLog(@"%@",texe);
                }
                if([texe hasPrefix:@"主要"]||[texe hasPrefix:@"住宅"])
                {
                    if([texe hasPrefix:@"主要"])
                    {
                        NSArray *lisd =[texe componentsSeparatedByString:@":"];
                        NSString *df =[lisd objectAtIndex:1];
                        _addressBook.main =df;
                    }
                    else
                    {
                        NSArray *lisd =[texe componentsSeparatedByString:@":"];
                        NSString *df =[lisd objectAtIndex:1];
                        _addressBook.main =df;
                    }
                }
            }
            CFRelease(person);
        }
        FMDBManager* manager = [FMDBManager sharedManager];
        [manager addUser:_addressBook];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
